package com.g2room.driving.grap.article.qg;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.g2room.driving.grap.article.to.ImgTo;
import com.g2room.driving.util.Constants;
import com.g2room.driving.util.DbUtil;
import com.g2room.driving.util.ImageUtil;

public class HandleImages {
	static String localImgDir = Constants.localImgDir;
	/**
	 * key为old src，value为true
	 */
	public static Map<String, Boolean> imgExits = new HashMap<String, Boolean>();
	public static List<ImgTo> imgTos = new ArrayList<ImgTo>();
//	private static Map<String, Boolean> imgMap = new HashMap<String, Boolean>();
	static List<String> grapedImage = getImgData();
	public static void main(String[] args) {
		getImgs("");
	}
	
	public static void getContentImgs(List<Integer> ids, String baseUrl, String dir) {
		System.out.println("准备抓取内容图片：" +  ids.size() + "==" + ids.toString());
		getImageSrc(ids, baseUrl);
		getImgs(dir);
	}
	/**
	 * 抓取缩略图
	 * @param ids
	 * @param baseUrl
	 * @param dir
	 */
	public static void getThumbImgs(List<Integer> ids, String baseUrl, String dir) {
		System.out.println("准备抓取缩略图：" + ids.toString());
		getThunbImageSrc(ids);
//		getImgs(dir + "/thumb", 1);
	}

	
	public static void getImgs(String dir) {
		StringBuffer errSrcSb = new StringBuffer();
		for(ImgTo it : imgTos) {
			if(!it.getGrapSrc().startsWith("http://") 
					) {
				continue;
			}
			try {
				String filePath = ImageUtil.downloadImage(it.getGrapSrc(), localImgDir, (it.getType() == 0 ? dir: dir+"/thumb"), null);
				insertImg(it, filePath, it.getType());
			} catch (Exception e) {
				System.out.println(it.getGrapSrc() + "\n");
				e.printStackTrace();
			}
		}
		DbUtil.closeConn();
		// 生成update语句
		System.out.println(errSrcSb.toString());
	}
	
	/**
	 * 获取缩略图图片地址
	 */
	public static void getThunbImageSrc(List<Integer> ids) {
		try {
			imgTos.clear();
			String idsSql = "";
			if(null == ids || ids.size() == 0) return;
			for(Integer id: ids) {
				if(idsSql.length() > 0) idsSql += ",";
				idsSql += id;
			}
			System.out.println("img数据ids：" + idsSql);
			if(idsSql.length() > 0) idsSql = " id in (" + idsSql + ") ";
			Connection connection = DbUtil.getQgshConn();
			Statement statement = connection.createStatement();
			String sql = "select id,thumb from d_article_grap where " + idsSql;
			ResultSet rs = statement.executeQuery(sql);
			while(rs.next()) {
				String thumb = rs.getString("thumb");
				if(null == thumb || thumb.length() == 0) continue;
				// 提取src值
				if(grapedImage.contains(thumb)) continue;
				grapedImage.add(thumb);
				ImgTo it = new ImgTo();
				it.setGrapSrc(thumb);
				it.setOldSrc(thumb);
				it.setId(rs.getInt("id"));
				// 不存在才去抓取
				imgTos.add(it);
			}
			rs.close();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取所有的图片地址
	 */
	public static void getImageSrc(List<Integer> ids, String baseUrl) {
		try {
			imgTos.clear();
			String idsSql = "";
			if(null == ids || ids.size() == 0) return;
			for(Integer id: ids) {
				if(idsSql.length() > 0) idsSql += ",";
				idsSql += id;
			}
			System.out.println("img数据ids：" + idsSql);
			if(idsSql.length() > 0) idsSql = " id in (" + idsSql + ") ";
			Connection connection = DbUtil.getQgshConn();
			Statement statement = connection.createStatement();
			String sql = "select id,type_name,content,thumb from d_article_grap where " + idsSql;
			ResultSet rs = statement.executeQuery(sql);
			String oldSrc = "";
			while(rs.next()) {
				String thumb = rs.getString("thumb");
				// 不存在才去抓取
				if(null != thumb && thumb.trim().startsWith("http") && !grapedImage.contains(thumb)) {
					ImgTo it = new ImgTo();
					it.setGrapSrc(thumb);
					it.setOldSrc(thumb);
					it.setId(rs.getInt("id"));
					it.setType(1);
					imgTos.add(it);
				}
				String content = rs.getString("content");
				if(!content.contains("<img")) continue;
				// 提取src值
				List<String> imgs = ImageUtil.getImgSrc(content);
				for(String src : imgs) {
					if(null == src || src.length() == 0 || src.contains("kaichejiqiao.cn") || grapedImage.contains(src)) continue;
					oldSrc = src;
					if(grapedImage.contains(src)) continue;
					grapedImage.add(oldSrc);
					src = (src.startsWith("http://") ? src : baseUrl
							+ (src.contains("../../../") ? src.replace("../../..", "") : src))
							.replaceAll(" ", "%20");
					ImgTo it = new ImgTo();
					it.setGrapSrc(src);
					it.setOldSrc(oldSrc);
					it.setId(rs.getInt("id"));
					// 不存在才去抓取
					imgTos.add(it);
				}
			}
			rs.close();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @param oldSrc
	 * @param grapSrc
	 * @param localSrc
	 * @param type
	 */
	public static void insertImg(ImgTo it, String localSrc, int type) {
		try {
			Connection connection = DbUtil.getQgshConn();
			PreparedStatement statement = connection.prepareStatement("insert into d_images(oldSrc, grapSrc, localSrc, type, artiId) values(?, ?, ?, ?, ?)");
			statement.setString(1, it.getOldSrc());
			statement.setString(2, it.getGrapSrc());
			statement.setString(3, localSrc);
			statement.setInt(4, type);
			statement.setInt(5, it.getId());
			statement.execute();
			statement.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	

	
	/**
	 * 获取已经抓取的了图片sql，从d_images
	 * @return
	 */
	public static List<String> getImgData() {
		String sql = "select oldSrc from d_images";
		List<String> imgs = new ArrayList<String>();
		try {
			Connection connection = DbUtil.getQgshConn();
			Statement statement = connection.createStatement();
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				imgs.add(rs.getString("oldSrc"));
			}
			rs.close();
			statement.close();
//			connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return imgs;
	}
}
